package raspberry_pi_app;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

public class ClassSocket {
	
	private ClassUberLogger logger;
	private ClassHttpHelper helper;
	private SocketIO socket;
	private boolean socket_registered, session_registered, force_retry;
	
	ClassSocket(ClassHttpHelper helper){
		logger = new ClassUberLogger("ClassSocket");
		this.helper = helper;
		socket_registered = false;
		session_registered = false;
		force_retry = false;
		create_socket();
		init_socket_events();
	}
	
	public SocketIO get_socket(){
		return socket;
	}
	
	public boolean needs_retry(){
		return force_retry;
	}
	
	public boolean has_full_connection(){
		return socket_registered && session_registered;
	}
	
	private void create_socket(){
		
		String host = helper.get_base_url();
		logger.info(host);
		Properties headers = new Properties();
		logger.info("Cookie Store Size: " + helper.get_client().get_cookies().getCookies().size());
		for (Cookie cookie : helper.get_client().get_cookies().getCookies()){
			
			logger.info(cookie.getDomain());
			logger.info(cookie.getName());
			logger.info(cookie.getValue());
			
			if (helper.get_base_url().contains(cookie.getDomain())){
				logger.info("Cookie Properties Set");
				Date date = new Date();
			    date.setTime(date.getTime()+(100*24*60*60*1000));
				String expires = "; expires="+date+";";
				headers.setProperty("Cookie", cookie.getName()+"="+cookie.getValue()+expires+" path=/;domain="+cookie.getDomain());
			}
		}
		try {
			socket = new SocketIO(host,headers);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void init_socket_events(){
        socket.connect(new IOCallback() {
            @Override
            public void onMessage(JSONObject json, IOAcknowledge ack) {
                try {
                    System.out.println("Server said:" + json.toString(2));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMessage(String data, IOAcknowledge ack) {
                System.out.println("Server said: " + data);
            }

            @Override
            public void onError(SocketIOException socketIOException) {
                System.out.println("an Error occured");
                socketIOException.printStackTrace();
            }

            @Override
            public void onDisconnect() {
                System.out.println("Connection terminated.");
            }

            @Override
            public void onConnect() {
                System.out.println("Connection established");
            }

            @Override
            public void on(String event, IOAcknowledge ack, Object... args) {
                System.out.println("Server triggered event '" + event + "'");
                
                if(event.equals("parse_user")){
                	socket_registered = true;
	                try {
	                	logger.info("Before");
		                JSONObject result_object = new JSONObject(args[0].toString());
						logger.info(result_object.toString());
		                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
						pairs.add(new BasicNameValuePair("email", result_object.getString("email")));
						result_object = new JSONObject(helper.postResponsefromURL("login/", pairs));
						logger.info("After");
						logger.info(result_object.toString());
						if(result_object.getString("action").equals("success")){
							session_registered = true;
							force_retry = false;
						}else{
							force_retry = true;
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }
            }
        });
	}
}
